import time

class SnowflakeGenerator:
    def __init__(self, worker_id: int, datacenter_id: int):
        self.worker_id = worker_id
        self.datacenter_id = datacenter_id
        self.sequence = 0
        self.last_timestamp = -1

    def _generate_timestamp(self):
        return int(time.time() * 1000)

    def generate_id(self):
        timestamp = self._generate_timestamp()

        if timestamp == self.last_timestamp:
            self.sequence = (self.sequence + 1) & 4095
            if self.sequence == 0:
                timestamp = self._til_next_millis()
        else:
            self.sequence = 0

        self.last_timestamp = timestamp

        snowflake_id = ((timestamp - 1288834974657) << 22) | (self.datacenter_id << 17) | \
                       (self.worker_id << 12) | self.sequence

        return snowflake_id

    def _til_next_millis(self):
        timestamp = self._generate_timestamp()
        while timestamp <= self.last_timestamp:
            timestamp = self._generate_timestamp()
        return timestamp

if __name__ == "__main__":
    print(SnowflakeGenerator(1,1).generate_id())
